<template>
  <div
    id="shopDet"
    class="main df"
    style="align-items: normal; justify-content: space-between"
  >
    <div class="left">
      <div class="df" style="align-items: normal; margin-top: 20px">
        <div>
          <div class="img-box">
            <img class="img" :src="bannerInfoList.infoBanner" alt="" />
            <div class="df" style="margin-top: 5px">
              <img
                class="banner-pic"
                :class="{ active: isActive == index }"
                @mouseenter="handleEnter(item, index)"
                v-for="(item, index) in goodsDetData.bannersPicUrl"
                :key="item"
                :src="item"
                alt=""
              />
            </div>
          </div>
        </div>
        <div>
          <div>升学讲堂</div>
          <span class="f14 zy">
            <el-checkbox v-model="checkAll" @change="handleCheckAllChange">
              全部课程
            </el-checkbox>
            <el-checkbox-group
              v-model="checkedCities"
              @change="handleCheckedCitiesChange"
            >
              <el-checkbox
                v-for="item in goodsType"
                :key="item.id"
                :label="item.name"
                :value="item.name"
              >
                {{ item.name }}
              </el-checkbox>
            </el-checkbox-group>
          </span>
          <div class="df">
            <div class="df" style="color: red">
              <div>
                限时：{{
                  checkAll ? (totalPrice.discountedPrice ?? 0) : AllPrice
                }}
              </div>
              <div class="df">
                <div class="f12">￥</div>
                <div
                  style="
                    font-size: 30px;
                    margin-bottom: 10px;
                    margin-right: 40px;
                  "
                >
                  {{ goodsDetData.realPrice }}
                </div>
              </div>
            </div>
            <div
              v-if="checkAll"
              style="color: #999; text-decoration: line-through"
            >
              原价 <span>￥</span> {{ totalPrice.price ?? '0.00' }}
            </div>
          </div>
          <div class="btn-box">
            <el-button
              :disabled="
                (checkLength.length <= 0 && !checkAll) ||
                (checkAll ? (totalPrice.discountedPrice ?? 0) : AllPrice) == 0
              "
              class="btn"
              @click="handleBuy"
              >购买服务{{ totalPrice.discountedPrice }}</el-button
            >
            <div class="lighting"></div>
          </div>
          <div class="hot-phone">
            咨询热线：{{ goodsDetData.phone ?? '028 - 84444696' }}
          </div>
        </div>
      </div>
      <div style="margin-top: 20px" class="f24">详情介绍</div>
      <div
        style="
          width: 100%;
          border-bottom: 1px solid black;
          margin: 5px 0 10px 0;
        "
      ></div>
      <div v-html="bannerInfoList.info"></div>
    </div>
    <!-- <div class="right-card">
      <teacher-team :expertsTeamList="expertsTeamList" />
    </div> -->
  </div>
  <buy-mask ref="maskRef" :goodsDetData="goodsDetData" />

  <Dialog
    :title="title"
    v-model="modelValue"
    width="600"
    @closePayDialog="closePayDialog"
  >
    <template #content>
      <div class="qrcode">
        <div class="boxCoverCode" v-loading="imgLoading">
          <img :src="code_url" alt="" class="qrImage" />
          <p>{{ goodsName }}</p>
          <p>{{ formattedTime }}</p>
          <p class="switch" @click="switchPayment">
            切换至{{ status ? '支付宝' : '微信' }}
          </p>
        </div>
        <div class="wx">
          <i v-if="status" class="iconfont icon-weixin1"></i>
          <i v-else class="iconfont icon-zhifubao"></i>
        </div>
      </div>
    </template>
  </Dialog>
</template>

<script setup>
import {
  classTypeListApi,
  singleCoursePayApi,
  verifyApi,
  AlipayToolApi,
  bannerInfoyApi,
} from '@/api/zy/index';
import QRCode from 'qrcode';
import Dialog from '@/components/Dialog/payDialog.vue';
// import { getServicesGet } from '@/api/shopServe/shopServe'; //getExpertsTeamList
// import TeacherTeam from '@/views/shopServe/components/TeacherTeam';
import BuyMask from './components/BuyMask';
import { ref, computed } from 'vue';
const timeRemaining = ref(300); // 倒计时时间，单位：秒（5 分钟）
const imgLoading = ref(false);
const code_url = ref('');
const title = ref('微信扫码支付');
const out_trade_no = ref('');
const goodsName = ref('');
const paymentStatus = ref(''); // 支付状态：空、success、failed
const bannerInfoList = ref([]);
const modelValue = ref(false);
const goodsType = ref([]);
const maskRef = ref(null);
const bigPic = ref('');
const isActive = ref(0);
const checkAll = ref(true);
const checkedCities = ref([]);
const goodsDetData = ref({});
const totalPrice = ref('');
const AllPrice = ref('');
const status = ref(true);
const params = ref({
  id: '',
  type: 3,
});
const checkLength = ref([]);
const handleCheckAllChange = (val) => {
  if (!val) {
    checkedCities.value = [];
  } else {
    checkedCities.value = goodsType.value.map((item) => item.name);
    params.value.id = goodsType.value.map((item) => item.id);
    params.value.type = 3;
  }
};
const handleCheckedCitiesChange = (val) => {
  checkLength.value = val;
  checkAll.value = val.length === goodsType.value.length;

  AllPrice.value = goodsType.value
    .filter((item) => val.includes(item.name)) // 筛选出匹配的项
    .reduce((sum, item) => sum + parseFloat(item.typePrice), 0); // 累加价格

  // 筛选匹配项并提取 id
  params.value.id = goodsType.value
    .filter((item) => val.includes(item.name)) // 筛选匹配的项目
    .map((item) => item.id); // 提取 id
  checkAll.value ? (params.value.type = 3) : (params.value.type = 2);
};
// 倒计时格式化为分钟和秒
const formattedTime = computed(() => {
  const minutes = Math.floor(timeRemaining.value / 60);
  const seconds = timeRemaining.value % 60;
  return (
    '请在' +
    `${minutes.toString().padStart(2, '0')}分${seconds.toString().padStart(2, '0')}` +
    '秒内完成支付'
  );
});
const handleBuy = () => {
  modelValue.value = true;
  imgLoading.value = true;
  code(params.value);
};
const code = async (params) => {
  const data = status.value
    ? await singleCoursePayApi(params)
    : await AlipayToolApi(params);
  if (data.data.code == 20000) {
    out_trade_no.value = data.data.data.out_trade_no;
    QRCode.toDataURL(data.data.data.code_url)
      .then((url) => {
        code_url.value = url;
        timeRemaining.value = 300; // 重置倒计时
        startCountdown(); // 开始倒计时
        startPolling(); // 开始轮询
        imgLoading.value = false;
      })
      .catch((error) => {
        console.error('二维码生成失败:', error);
      });
  }
};

// 切换支付
const switchPayment = () => {
  status.value = !status.value;
  status.value
    ? (title.value = '微信扫码支付')
    : (title.value = '支付宝扫码支付');
  code(params.value);
};

// 倒计时逻辑
let countdownInterval;
const startCountdown = () => {
  clearInterval(countdownInterval); // 清除之前的倒计时
  countdownInterval = setInterval(() => {
    if (timeRemaining.value > 0) {
      timeRemaining.value -= 1;
    } else {
      clearInterval(countdownInterval); // 倒计时结束时停止计时
      stopPolling(); // 停止轮询
    }
  }, 1000);
};

// 轮询支付状态逻辑
let pollingInterval;
const startPolling = () => {
  clearInterval(pollingInterval); // 清除之前的轮询
  pollingInterval = setInterval(async () => {
    try {
      const response = await verifyApi({ out_trade_no: out_trade_no.value }); // 模拟后端请求
      if (response.data.msg === '购买成功') {
        paymentStatus.value = '购买成功';
        clearInterval(pollingInterval); // 停止轮询
        clearInterval(countdownInterval); // 停止倒计时
        modelValue.value = false;
      }
    } catch (error) {
      console.error('轮询支付状态失败:', error);
    }
  }, 5000); // 每 5 秒轮询一次
};

// 停止轮询
const stopPolling = () => {
  clearInterval(pollingInterval);
};

const closePayDialog = () => {
  stopPolling();
};

const handleEnter = (item, index) => {
  isActive.value = index;
  bigPic.value = item;
};

// const fetchServicesGet = () => {
//   getServicesGet().then((res) => {
//     if (res.data.code == 20000) {
//       console.log(res, 'res');
//       goodsDetData.value = res.data.data;
//       if (res.data.data.bannersPicUrl) {
//         goodsDetData.value.bannersPicUrl =
//           res.data.data.bannersPicUrl.split(',');
//       } else {
//         goodsDetData.value.bannersPicUrl = [noGood];
//       }
//       bigPic.value = goodsDetData.value.bannersPicUrl[0];
//     }
//   });
// };
// const expertsTeamList = ref([]);
// const fetchExpertsTeamList = () => {
//   getExpertsTeamList().then((res) => {
//     if (res.data.code == 20000) {
//       expertsTeamList.value = res.data.data.slice(0, 3);
//     }
//   });
// };
// fetchExpertsTeamList();
// 第一个轮播跳转
const bannerInfo = async () => {
  const data = await bannerInfoyApi();
  bannerInfoList.value = data.data.data;
};
const inti = async () => {
  const { data } = await classTypeListApi({ page: 1, pageSize: 100 });
  goodsType.value = data.data.data;
  checkedCities.value = goodsType.value.map((item) => item.name);
  // 总价
  totalPrice.value = data.data.totalPrice;
  if (checkAll.value) params.value.id = goodsType.value.map((item) => item.id);
};

inti();
bannerInfo();
</script>

<style lang="scss" scoped>
#shopDet {
  padding: 20px;
  .banner-pic {
    width: 80px;
    height: 60px;
    margin: 0 10px 0 0;
    cursor: pointer;
  }
  .banner-pic:nth-child(4) {
    margin-right: 0px;
  }
  .img-box {
    margin-right: 20px;
    .img {
      width: 350px;
      height: 255px;
    }
  }
  .btn-box {
    height: 50px;
    .btn {
      height: 40px;
      width: 320px;
      background-color: var(--background-color);
      color: var(--text-color);
    }
    .lighting {
      width: 30px;
      height: 60px;
      position: relative;
      top: -55px;
      left: -80px;
      transform: rotate(15deg);
      -webkit-transform: rotate(15deg);
      -webkit-animation: lighting 1.2s linear infinite forwards;
      -moz-animation: lighting 1.2s linear infinite forwards;
      animation: lighting 1.2s linear infinite forwards;
      background: rgba(255, 255, 255, 0.4);
      z-index: 1;
    }
    @keyframes lighting {
      from {
        left: 0px; /* 起始位置 */
      }
      to {
        left: calc(100% + 0px); /* 结束位置，需根据实际情况调整偏移量 */
      }
    }
  }
  .hot-phone {
    height: 21px;
    font-size: 14px;
    font-weight: 400;
    color: #666;
    line-height: 21px;
  }
}
.active {
  border: 1px solid var(--color-text);
}
.zy {
  color: #666;
  margin: 20px 0 30px 0;
  display: inline-block;
  margin-right: 10px;
  cursor: pointer;
}
.zy:hover {
  color: red;
}
.zy.active {
  color: red;
}
.qrcode {
  text-align: center;
  .boxCoverCode {
    position: relative;
  }
  .wx {
    width: 50px;
    position: absolute;
    left: 50%;
    top: 50%;
    background-color: #fff;
    border-radius: 6px;
    transform: translate(-50%, -50%);
    .icon-weixin1 {
      color: green;
      font-size: 30px;
    }
    .icon-zhifubao {
      color: rgb(6, 180, 253);
      font-size: 30px;
    }
  }
}
.qrImage {
  width: 300px;
  height: 300px;
}
.switch {
  cursor: pointer;
  font-weight: 400;
  font-size: 14px;
  color: #72030d;
}
</style>
